package com.binvshe.binvshe.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.binvshe.binvshe.R;
import com.f2prateek.dart.Dart;
import com.f2prateek.dart.InjectExtra;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.baidumaplib.location.overlayutil.DrivingRouteOverlay;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Zoi.
 * E-mail：KyluZoi@gmail.com
 * 2017/1/23
 */

public class MapActivity extends BaseActivity implements OnGetRoutePlanResultListener {

    private static final String KEY_DATA = "DATA";

    @Bind(R.id.baiduMapView)
    MapView mBaiduMapView;


    RoutePlanSearch mSearch;
    LatLng point;//目标位置
    LatLng myLocation = null;//自己位置
    BaiduMap baiduMap;
    DrivingRouteOverlay drivingOverlay;
    PoiSearch poiSearch;//检索接口

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();


    @Bind(R.id.btnJumpMap)
    TextView mBtnJumpMap;
    @Bind(R.id.tvPlace)
    TextView mTvPlace;

    @InjectExtra(KEY_DATA)
    ActivityEntity mData;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化sdk
        SDKInitializer.initialize(getApplicationContext());
        ButterKnife.bind(this);
        Dart.inject(this);
        baiduMap = mBaiduMapView.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //将BaiduMap的setMyLocationEnabled设置为True
        baiduMap.setMyLocationEnabled(true);
        //初始化位置的确定
        LatLng cenpt =  new LatLng(33.242544, 108.808425);

        initPoint(baiduMap);

        mTvPlace.setText(mData.getAddress());

        //定义Maker坐标点
        //// FIXME: 2017/1/24 活动地点定位位置
        enableBackButton();
        getCustomToolbar().setTitle("地图详情");
        point = new LatLng(mData.getLatitude(), mData.getLongitude());
        mLocationClient = new LocationClient(this);     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
//        mLocationClient.start();

        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.ease_icon_marka);//标记图标
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .zIndex(5)
                .icon(bitmap);
//        OverlayOptions option1 = new MarkerOptions()
//                .position(myLocation)
//                .zIndex(5)
//                .icon(bitmap);
        //在地图上添加Marker，并显示
        baiduMap.addOverlay(option);
//        baiduMap.addOverlay(option1);
        drivingOverlay = new DrivingRouteOverlay(baiduMap);
        //定位到point
        MapStatus mapStatus = new MapStatus.Builder().target(point).zoom(18).build();
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
        baiduMap.setMapStatus(mapStatusUpdate);


        baiduMap.setOnMarkerClickListener(drivingOverlay);
        final PlanNode fromPlanNode = PlanNode.withLocation(myLocation);
        final PlanNode toPlanNode = PlanNode.withLocation(point);
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        Log.d("MapActivity", "开始规划");
        mBtnJumpMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSearch.drivingSearch(new DrivingRoutePlanOption().from(fromPlanNode).to(toPlanNode));
                Log.d("MapActivity", "click");
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mBaiduMapView.onResume();
    }

    @Override
    protected void onPause() {
        mBaiduMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mBaiduMapView.onDestroy();
        super.onDestroy();
    }

    public static void start(Context context, ActivityEntity data) {
        Intent starter = new Intent(context, MapActivity.class);
        starter.putExtra(KEY_DATA, data);
        context.startActivity(starter);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_map, null);
    }

    /**
     * 设置标记
     */
    private void initPoint(BaiduMap baiduMap) {

    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        Log.d("MapActivity", "11");
    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {
        Log.d("MapActivity", "22");
    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {
        Log.d("MapActivity", "33");
    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult result) {
        if (myLocation == null) {
            Toast.makeText(this, "正在获取个人位置", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d("MapActivity", "驾车回调");
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT).show();
            Log.d("MapActivity", "无结果");
            return;
        }
        Log.d("MapActivity", "result.getRouteLines().size():" + result.getRouteLines().size());
        List<DrivingRouteLine> routeLines = result.getRouteLines();
        baiduMap.clear();
        drivingOverlay.removeFromMap();
        drivingOverlay.setData(routeLines.get(0));
        drivingOverlay.addToMap();
        drivingOverlay.zoomToSpan();
    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {
        Log.d("MapActivity", "44");

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
        Log.d("MapActivity", "55");

    }

    private void startSearch(LatLng start, LatLng end) {
        PlanNode stNode = PlanNode.withLocation(start);
        PlanNode enNode = PlanNode.withLocation(end);
        mSearch.drivingSearch((new DrivingRoutePlanOption()).from(stNode).to(enNode));
    }


    /**
     * 定位监听
     */
    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) {
                Toast.makeText(MapActivity.this, "定位失败",
                        Toast.LENGTH_SHORT).show();
                return;
            }
            //Receive Location
            Log.e("MyLocationListener","MyLocationListener ==" +"进");
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            myLocation = new LatLng(location.getLongitude(), location.getLatitude());
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());
        }
    }

}
